﻿package net.wangit.dev.unit;

import net.wangit.Element;
import net.wangit.MapList;
import net.wangit.Row;
import net.wangit.Unit;
import net.wangit.context.ActionContext;
import net.wangit.dev.ConsoleDomainUtil;
import net.wangit.dev.component.ObjectTreeHelper;
import net.wangit.framework.util.QueryProcessor;
import net.wangit.jdbc.DB;
import net.wangit.jdbc.DBImplementor;
import net.wangit.jdbc.util.DBHelper;
import net.wangit.support.UnitInterceptor;
import net.wangit.util.Checker;
import net.wangit.view.unit.UnitComponent;

public class SelectResourceUI implements UnitInterceptor {

	private static final String SQL = "select * from UNIT";
	private static final String ICON_PATH = "/domain/dev/u/";

	public SelectResourceUI() {
	}

	public String intercept(ActionContext ac, Unit unit) throws Exception {
		String domain = ConsoleDomainUtil.getDomain(ac);
		DB db = DBHelper.getDomainDB(domain);
		UnitComponent uc = (UnitComponent) unit;
		String sql = QueryProcessor.addConditionAndOrder(ac,
				(DBImplementor) db, SelectResourceUI.SQL, domain, uc
						.getQueryUnitId(), uc.getTableName(), null);
		MapList data = db.query(sql);
		if (!Checker.isEmpty(data)) {
			Element icon = unit.getElement("icon");
			for (int i = 0; i < data.size(); i++) {
				Row row = data.getRow(i);
				String link = (new StringBuilder(SelectResourceUI.ICON_PATH))
						.append(
								ObjectTreeHelper.getUnitIcon(db,
										row.get("uid"), row, true)).toString();
				icon.setLink(i, link);
			}

		}
		unit.setData(data);
		return unit.write(ac);
	}
}
